Page({
  data: {
    records: [
      {
        id: '1',
        title: '青岛海域捕捞',
        boatNumber: '鲁即渔12375',
        time: '2024-03-20 14:30',
        location: '青岛海域',
        fisher: '张三'
      },
      {
        id: '2',
        title: '威海海域捕捞',
        boatNumber: '鲁即渔12376',
        time: '2024-03-19 15:45',
        location: '威海海域',
        fisher: '李四'
      }
    ],
    showQrcode: false,
    selectedRecord: null,
    showActions: false,
    actions: [
      { name: '生成二维码', value: 'qrcode' },
      { name: '删除', value: 'delete', color: '#e34d59' }
    ]
  },

  onLoad() {
    this.loadRecords();
  },

  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 3
      });
    }
  },

  loadRecords() {
    // 加载捕捞记录
    wx.request({
      url: 'https://api.example.com/records',
      method: 'GET',
      success: (res) => {
        if (res.data.success) {
          this.setData({
            records: res.data.data
          });
        }
      }
    });
  },

  onSearch(e) {
    const keyword = e.detail.value;
    // 搜索捕捞记录
    wx.request({
      url: 'https://api.example.com/records/search',
      method: 'GET',
      data: {
        keyword
      },
      success: (res) => {
        if (res.data.success) {
          this.setData({
            records: res.data.data
          });
        }
      }
    });
  },

  showActionSheet(e) {
    const record = e.currentTarget.dataset.record;
    this.setData({
      selectedRecord: record,
      showActions: true
    });
  },

  closeActionSheet() {
    this.setData({
      showActions: false
    });
  },

  onActionClick(e) {
    const { value } = e.detail;
    const { selectedRecord } = this.data;

    switch (value) {
      case 'qrcode':
        this.setData({
          showQrcode: true
        });
        break;
      case 'delete':
        this.deleteRecord(selectedRecord.id);
        break;
    }

    this.closeActionSheet();
  },

  onQrcodeClose() {
    this.setData({
      showQrcode: false
    });
  },

  deleteRecord(id) {
    wx.showModal({
      title: '提示',
      content: '确定要删除该捕捞记录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: 'https://api.example.com/records/delete',
            method: 'POST',
            data: {
              id
            },
            success: (res) => {
              if (res.data.success) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                this.loadRecords();
              }
            }
          });
        }
      }
    });
  },

  addRecord() {
    wx.navigateTo({
      url: '/pages/fishing/add/index'
    });
  },

  onRecordClick(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/fishing/detail/index?id=${id}`
    });
  },

  goBack() {
    wx.navigateBack();
  }
});